package com.ycy.listener;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEventType;
import org.flowable.engine.*;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.runtime.ProcessInstanceBuilder;
import org.flowable.task.api.Task;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TransactionFlowableListenerTest {


  ProcessEngine processEngine;

  ProcessEngineConfiguration cfg;

  @Before
  public void before() {
    cfg = new StandaloneProcessEngineConfiguration()
//                .setJdbcUrl("jdbc:h2:mem:flowable;DB_CLOSE_DELAY=-1")
//                .setJdbcDriver("org.h2.Driver")
//                .setJdbcUsername("sa")
            .setJdbcPassword("")
            .setJdbcUrl("jdbc:mysql://127.0.0.1:3306/flowablebp?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8")
            .setJdbcUsername("root")
            .setJdbcPassword("123456")
            .setJdbcDriver("com.mysql.jdbc.Driver")

            // 如果数据表不存在的时候，自动创建数据表
            .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);

    //添加监听
    List<FlowableEventListener> eventListeners = new ArrayList<>();

    TransactionCommittedFlowableListener ycyTransactionCommittedFlowableListener
            = new TransactionCommittedFlowableListener();
    eventListeners.add(ycyTransactionCommittedFlowableListener);

    TransactionRollerBackFlowableListener transactionRollerBackFlowableListener = new TransactionRollerBackFlowableListener();
    eventListeners.add(transactionRollerBackFlowableListener);

    eventListeners.add(new TransactionCommittingFlowableListener());

    this.cfg.setEventListeners(eventListeners);

    // 执行完成后，就可以开始创建我们的流程了
    processEngine = cfg.buildProcessEngine();
    ycyTransactionCommittedFlowableListener.setProcessEngine(processEngine);

    transactionRollerBackFlowableListener.setProcessEngine(processEngine);
  }

  @Test
  public void create(){
    // 部署流程
    RepositoryService repositoryService = processEngine.getRepositoryService();
    Deployment deployment = repositoryService.createDeployment()
            .addClasspathResource("listener/holiday-request.bpmn20.xml")
            .deploy();
  }

  //发起流程 带监听
  @Test
  public void listener() {
    RuntimeService runtimeService = processEngine.getRuntimeService();
    //创建流程实例
    ProcessInstanceBuilder processInstanceBuilder = runtimeService.createProcessInstanceBuilder();
    for (int i = 0; i < 1; i++) {
      Long currentTime = System.currentTimeMillis();
      Map<String, Object> variables = new HashMap<String, Object>();
      variables.put("employee", "employee" + currentTime);
      variables.put("nrOfHolidays", "nrOfHolidays" + currentTime);
      variables.put("description", "description" + currentTime);

      processInstanceBuilder.processDefinitionKey("holidayRequest")
              .businessKey(currentTime + "")
              .name("tiao")
              .variables(variables);

      ProcessInstance start = processInstanceBuilder.start();
      System.out.println(start.getBusinessKey());
      System.out.println(start.getId());
      System.out.println(start.getProcessInstanceId());
    }

  }

  /**
   * 审核通过 带监听
   */
  @Test
  public void listener2() {
    TaskService taskService = processEngine.getTaskService();
    List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list();
    System.out.println("You have " + tasks.size() + " tasks:");

    for (int i = 0; i < tasks.size(); i++) {
      Task task = tasks.get(i);
      String id = task.getId();
      //打印task任务信息
      System.out.println((i + 1) + ") " + id + " : " + task.getName() + " : " + task.getProcessInstanceId());
//1) 120009 : Approve or reject request : 120001
      //审核通过
      Map<String, Object> variables = new HashMap<String, Object>();
//      variables.put("approved", true);
      taskService.complete(id, variables);
      System.out.println(task.getTaskLocalVariables());

    }

  }

  //当流程完成最后一步时，会触发 PROCESS_COMPLETED 事件
  @Test
  public void test1() {
    TaskService taskService = processEngine.getTaskService();
    //获取 最后一步的 task
    List<Task> list = taskService.createTaskQuery().taskDefinitionKey("holidayApprovedTask").list();
    for (Task task : list) {
      System.out.println(task);
      taskService.complete(task.getId());
      //触发 PROCESS_COMPLETED
    }
  }

  //直接添加事件
  @Test
  public void listener3() {
    RuntimeService runtimeService = processEngine.getRuntimeService();
    runtimeService.dispatchEvent(new FlowableEvent() {
      @Override
      public FlowableEventType getType() {
        return FlowableEngineEventType.PROCESS_COMPLETED_WITH_ERROR_END_EVENT;
      }
    });

  }

  //直接添加事件
  @Test
  public void test(){
    TaskService taskService = processEngine.getTaskService();
    taskService.complete("5003");
  }


}
